/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.forward.mobile.optitrans.domain;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonWriter;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.util.List;

/**
 *
 * @author Tchiediougou
 */
public class GsonUtils {

    public static <T> void getGenericType(List<T> list, JsonWriter writer) {
        Type type = new TypeToken<List<T>>() {
        }.getType();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        gson.toJson(list, type, writer);
    }

    public static <T> void getGenericType(List<T> list, JsonWriter writer, boolean expose) {
        Type type = new TypeToken<List<T>>() {
        }.getType();
        GsonBuilder builder = new GsonBuilder();
        if (expose) {
            builder.excludeFieldsWithoutExposeAnnotation();
        }
        Gson gson = builder.create();
        gson.toJson(list, type, writer);
    }

    public static <T> void toGson(T list, PrintWriter pw, boolean excludue) {
        GsonBuilder builder = new GsonBuilder();
        if (excludue) {
            builder.excludeFieldsWithoutExposeAnnotation();
        }
        JsonWriter writer = new JsonWriter(pw);
        Gson gson = builder.create();
        JsonParser jsonParser = new JsonParser();
        JsonElement element = jsonParser.parse(gson.toJson(list));
        gson.toJson(element, writer);
    }
}
